package com.hxkcloud.patient.activitys;

import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.support.v4.content.ContextCompat;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.hxkcloud.patient.ActivityManager;
import com.hxkcloud.patient.R;
import com.hxkcloud.patient.beans.DoctorGroupBean;
import com.hxkcloud.patient.beans.MonitorKindBean;
import com.hxkcloud.patient.dborm.DoctorGroupDao;
import com.hxkcloud.patient.dborm.MonitorKindDao;
import com.hxkcloud.patient.fragments.DoctorMessageFragment;
import com.hxkcloud.patient.fragments.DoctorPatientsFragment;
import com.hxkcloud.patient.fragments.MineFragment;
import com.hxkcloud.patient.request.MessageCode;
import com.hxkcloud.patient.request.YiJiaHuNetWorkUtils;
import com.hxkcloud.patient.utils.BrightnessUtils;
import com.hxkcloud.patient.utils.SharedPreferenceUtil;
import com.hxkcloud.patient.views.MainViewPager;
import com.zhuge.analysis.stat.ZhugeSDK;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by william_sun on 2016-10-10.
 * Description:医生登录主界面
 */
public class DoctorFragmentActivity extends BaseFragmentActivity implements View.OnClickListener {

    public MainViewPager viewPager;
    public List<Fragment> fragments = new ArrayList<Fragment>();
    private ImageView iv_manage, iv_msg, iv_mine;
    private ImageView iv_msgpoint;
    private LinearLayout ll_manage, ll_msg, ll_mine;
    private TextView tv_manage, tv_msg, tv_mine;
    private FragmentManager fragmentManager;
    private int currIndex = 0;// 当前页卡编号
    public boolean getbasic = false;//是否需要获取一些基本数据
    //医生端不需要文章类型了
    private DoctorPatientsFragment doctorPatientsFragment;
    private DoctorMessageFragment doctorMessageFragment;
    private MineFragment mineFragment;

    public static DoctorFragmentActivity doctorFragmentActivity;

    @Override
    protected void updateByHandler(Message msg) {
        switch (msg.what) {
            case MessageCode.NETWORKCODE_MONITORKIND_SUCCESS:
                List<MonitorKindBean> kinds = (List<MonitorKindBean>) msg.obj;
                if (kinds != null && kinds.size() > 0) {
                    MonitorKindDao monitorKindDao = new MonitorKindDao(mContext);
                    monitorKindDao.setKind(kinds, "1");
                }
                break;
            case MessageCode.MSG_CHECKNEWMSG_HAVE:
//                discoverFragment.showPoint(true);
//                userManagerFragment.showPoint(true, jpushType);
//                assistantFragment.showPoint(true);
//                mineFragment.showPoint(true);

                //下面的消息图标加红点，消息页jpushType加红点
                iv_msgpoint.setVisibility(View.VISIBLE);
                doctorMessageFragment.haveNewMsg();
                break;
            case MessageCode.MSG_CHECKNEWMSG_HAVENOT:
//                discoverFragment.showPoint(false);
//                userManagerFragment.showPoint(false, jpushType);
//                assistantFragment.showPoint(false);
//                mineFragment.showPoint(false);
                iv_msgpoint.setVisibility(View.GONE);
                break;
            case MessageCode.NETWORKCODE_GETDOCTORGROULIST_SUCCESS:
                List<DoctorGroupBean> groups = (List<DoctorGroupBean>) msg.obj;
                if (groups != null && groups.size() > 0) {
                    DoctorGroupDao doctorGroupDao = new DoctorGroupDao(mContext);
                    doctorGroupDao.setGroup(groups);
                }
                initPatientPopup();
                break;
            case MessageCode.MSG_FRAGMENTACTIVITYVERSIONUPDATE:
                popup_easynotice1.showAtLocation(viewPager, Gravity.CENTER, 0, 0);
                BrightnessUtils.lightOff(DoctorFragmentActivity.this);
                break;
        }
    }

    private void initPatientPopup() {
        if (doctorPatientsFragment != null) {
            handler.postDelayed(new Runnable() {
                @Override
                public void run() {
                    doctorPatientsFragment.initAllPopup();
                }
            }, 500);
        } else {
            System.out.println("doctorpfnull");
            handler.postDelayed(new Runnable() {
                @Override
                public void run() {
                    initPatientPopup();
                }
            }, 500);
        }
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_doctormain);

        currIndex = getIntent().getIntExtra("index", 0);
        getbasic = getIntent().getBooleanExtra("getbasic", false);
        initView();
        if (getbasic) {
            handler.postDelayed(new Runnable() {
                @Override
                public void run() {
                    YiJiaHuNetWorkUtils.getMonitorKind(loginInfo.getDepartmentId(), handler);
                    YiJiaHuNetWorkUtils.getDoctorGroupList(loginInfo.getDepartmentId(), handler);
                }
            }, 200);
        } else {
//            handler.postDelayed(new Runnable() {
//                @Override
//                public void run() {
//                    doctorPatientsFragment.initAllPopup();
//                }
//            }, 1000);
            initPatientPopup();
        }
        getNewMsg();
        judgeUpdate();
        doctorFragmentActivity = this;
    }

    private void initView() {
        viewPager = (MainViewPager) findViewById(R.id.viewPager_doctor);
        iv_manage = (ImageView) findViewById(R.id.iv_doctormain_manage);
        iv_msg = (ImageView) findViewById(R.id.iv_doctormain_msg);
        iv_mine = (ImageView) findViewById(R.id.iv_doctormain_mine);
        iv_msgpoint = (ImageView) findViewById(R.id.iv_doctormain_msgpoint);
        ll_manage = (LinearLayout) findViewById(R.id.ll_doctormain_manage);
        ll_msg = (LinearLayout) findViewById(R.id.ll_doctormain_msg);
        ll_mine = (LinearLayout) findViewById(R.id.ll_doctormain_mine);
        tv_manage = (TextView) findViewById(R.id.tv_doctormain_manage);
        tv_msg = (TextView) findViewById(R.id.tv_doctormain_msg);
        tv_mine = (TextView) findViewById(R.id.tv_doctormain_mine);

        doctorPatientsFragment = new DoctorPatientsFragment();
        doctorMessageFragment = new DoctorMessageFragment();
        mineFragment = new MineFragment();
        fragments.add(doctorPatientsFragment);
        fragments.add(doctorMessageFragment);
        fragments.add(mineFragment);

        fragmentManager = this.getSupportFragmentManager();

        viewPager.setSlipping(true);//设置ViewPager是否可以滑动
        viewPager.setOffscreenPageLimit(0);
        viewPager.addOnPageChangeListener(new MyOnPageChangeListener());
        viewPager.setAdapter(new MyPagerAdapter());
        viewPager.setCurrentItem(currIndex);

        ll_manage.setOnClickListener(this);
        ll_msg.setOnClickListener(this);
        ll_mine.setOnClickListener(this);

        LinearLayout.LayoutParams lp_bottom1 = new LinearLayout.LayoutParams((screenWidth / 15) - 5, (screenWidth / 15) - 5);
        LinearLayout.LayoutParams lp_bottom2 = new LinearLayout.LayoutParams((screenWidth / 10) - 7, (screenWidth / 15) - 5);
        RelativeLayout.LayoutParams lp_bottom3 = new RelativeLayout.LayoutParams((screenWidth / 15) - 5, (screenWidth / 15) - 5);
        iv_manage.setLayoutParams(lp_bottom2);
        iv_msg.setLayoutParams(lp_bottom3);
        iv_mine.setLayoutParams(lp_bottom1);

        if (currIndex == 1) {
            iv_manage.setImageResource(R.drawable.tab_manage);
            iv_msg.setImageResource(R.drawable.tab_message_pre);
            iv_mine.setImageResource(R.drawable.tab_my);
            tv_manage.setTextColor(ContextCompat.getColor(mContext, R.color.grey_text1));
            tv_msg.setTextColor(ContextCompat.getColor(mContext, R.color.light_blue));
            tv_mine.setTextColor(ContextCompat.getColor(mContext, R.color.grey_text1));
        } else if (currIndex == 2) {
            iv_manage.setImageResource(R.drawable.tab_manage);
            iv_msg.setImageResource(R.drawable.tab_message);
            iv_mine.setImageResource(R.drawable.tab_my_pre);
            tv_manage.setTextColor(ContextCompat.getColor(mContext, R.color.grey_text1));
            tv_msg.setTextColor(ContextCompat.getColor(mContext, R.color.grey_text1));
            tv_mine.setTextColor(ContextCompat.getColor(mContext, R.color.light_blue));
        } else {
            iv_manage.setImageResource(R.drawable.tab_manage_pre);
            iv_msg.setImageResource(R.drawable.tab_message);
            iv_mine.setImageResource(R.drawable.tab_my);
            tv_manage.setTextColor(ContextCompat.getColor(mContext, R.color.light_blue));
            tv_msg.setTextColor(ContextCompat.getColor(mContext, R.color.grey_text1));
            tv_mine.setTextColor(ContextCompat.getColor(mContext, R.color.grey_text1));
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
        Message msg = handler.obtainMessage(MessageCode.MSG_CHECKNEWMSG);
        msg.sendToTarget();
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.ll_doctormain_manage:
                viewPager.setCurrentItem(0);
                break;
            case R.id.ll_doctormain_msg:
                viewPager.setCurrentItem(1);
                break;
            case R.id.ll_doctormain_mine:
                viewPager.setCurrentItem(2);
                break;
        }
    }

    private class MyOnPageChangeListener implements ViewPager.OnPageChangeListener {

        @Override
        public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

        }

        @Override
        public void onPageSelected(int position) {
            switch (position) {
                case 0:
                    iv_manage.setImageResource(R.drawable.tab_manage_pre);
                    iv_msg.setImageResource(R.drawable.tab_message);
                    iv_mine.setImageResource(R.drawable.tab_my);
                    tv_manage.setTextColor(ContextCompat.getColor(mContext, R.color.light_blue));
                    tv_msg.setTextColor(ContextCompat.getColor(mContext, R.color.grey_text1));
                    tv_mine.setTextColor(ContextCompat.getColor(mContext, R.color.grey_text1));
                    break;
                case 1:
                    iv_manage.setImageResource(R.drawable.tab_manage);
                    iv_msg.setImageResource(R.drawable.tab_message_pre);
                    iv_mine.setImageResource(R.drawable.tab_my);
                    tv_manage.setTextColor(ContextCompat.getColor(mContext, R.color.grey_text1));
                    tv_msg.setTextColor(ContextCompat.getColor(mContext, R.color.light_blue));
                    tv_mine.setTextColor(ContextCompat.getColor(mContext, R.color.grey_text1));
                    break;
                case 2:
                    iv_manage.setImageResource(R.drawable.tab_manage);
                    iv_msg.setImageResource(R.drawable.tab_message);
                    iv_mine.setImageResource(R.drawable.tab_my_pre);
                    tv_manage.setTextColor(ContextCompat.getColor(mContext, R.color.grey_text1));
                    tv_msg.setTextColor(ContextCompat.getColor(mContext, R.color.grey_text1));
                    tv_mine.setTextColor(ContextCompat.getColor(mContext, R.color.light_blue));
                    break;
                default:
                    break;
            }
            currIndex = position;
        }

        @Override
        public void onPageScrollStateChanged(int state) {

        }
    }

    private class MyPagerAdapter extends PagerAdapter {

        @Override
        public int getCount() {
            return fragments.size();
        }

        @Override
        public boolean isViewFromObject(View view, Object object) {
            return view == object;
        }

//        @Override
//        public void destroyItem(View container, int position, Object object) {
//            ((ViewPager) container).removeView(fragments.get(position).getView());
//        }

        @Override
        public void destroyItem(ViewGroup container, int position, Object object) {
//            super.destroyItem(container, position, object);
            ((ViewPager) container).removeView(fragments.get(position).getView());
        }


        @Override
        public Object instantiateItem(ViewGroup container, int position) {
            Fragment fragment = fragments.get(position);
            if (!fragment.isAdded()) { // 如果fragment还没有added
                FragmentTransaction ft = fragmentManager.beginTransaction();
                ft.add(fragment, fragment.getClass().getSimpleName());
                ft.commit();
                /**
                 * 在用FragmentTransaction.commit()方法提交FragmentTransaction对象后
                 * 会在进程的主线程中,用异步的方式来执行。
                 * 如果想要立即执行这个等待中的操作,就要调用这个方法(只能在主线程中调用)。
                 * 要注意的是,所有的回调和相关的行为都会在这个调用中被执行完成,因此要仔细确认这个方法的调用位置。
                 */
                fragmentManager.executePendingTransactions();
            }

            if (fragment.getView().getParent() == null) {
                container.addView(fragment.getView()); // 为viewpager增加布局
            }
            return fragment.getView();
        }

    }

    private long exitTime = 0;

    @Override
    public boolean dispatchKeyEvent(KeyEvent event) {
        if (event.getKeyCode() == KeyEvent.KEYCODE_BACK && event.getAction() == KeyEvent.ACTION_DOWN && event.getRepeatCount() == 0) {
            if ((System.currentTimeMillis() - exitTime) > 2000) {
//                Toast.makeText(mContext, R.string.doubleback, Toast.LENGTH_LONG).show();
                toastMsg(R.string.doubleback);
                exitTime = System.currentTimeMillis();
            } else {
                cancelToast();
                SharedPreferenceUtil.setIsrunning(mContext, false);
//                MobclickAgent.onKillProcess(this);

                new Handler().postDelayed(new Runnable() {

                    @Override
                    public void run() {

                        finish();
                        ActivityManager.getInstance().removeAllActivity();
                        System.exit(0);
                        android.os.Process.killProcess(android.os.Process.myPid());
                    }
                }, 200);
                // finish();
                // System.exit(0);
            }
            return true;
        }
        return super.dispatchKeyEvent(event);
    }

    public static DoctorFragmentActivity getInstance() {
        return doctorFragmentActivity;
    }

//    private String jpushType = "";

    public void jpushNew(boolean changePage) {
        handler.sendEmptyMessage(MessageCode.MSG_CHECKNEWMSG_HAVE);
        if (changePage)
            viewPager.setCurrentItem(1);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        ZhugeSDK.getInstance().flush(getApplicationContext());
    }
}
